package ru.adhoc.truealarmfree.activities;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SeekBar;
import android.widget.TextView;

import com.google.analytics.tracking.android.EasyTracker;

import ru.adhoc.truealarmfree.R;
import ru.adhoc.truealarmfree.barcodreader.CameraTestActivity;
import ru.adhoc.truealarmfree.utils.Util;


/**
 * Created by Малюгин Сергей on 18.09.13.
 */
public class SettingsActivity extends PreferenceActivity implements
        Preference.OnPreferenceChangeListener {

    private Preference maxRepeat;
    private Preference barCode;
    private Preference rev;
    private Preference buy;
    private Preference about;
    private String version = "";
    private boolean barcodeDialog;

    private Context context;

    private CheckBoxPreference mCheckBoxPreferenceClassicOff;
    private CheckBoxPreference mCheckBoxPreferenceTextOff;
    private CheckBoxPreference mCheckBoxPreferenceBarCodeOff;
    private CheckBoxPreference mCheckBoxPreferenceMyBarCodeOff;

    private CheckBoxPreference chbBlueTheme;
    private CheckBoxPreference chbYellowTheme;
    private CheckBoxPreference chbChristmasTheme;

    private final String KEY_CLASSIC_OFF = "classicOff";
    private final String KEY_TEXT_OFF = "TextOff";
    private final String KEY_BARCODE_OFF = "barCodeOff";
    private final String KEY_MY_BARCODE_OFF = "useMyBarCode";

    private final String KEY_BLUE_THEME = "blue_theme";
    private final String KEY_YELLOW_THEME = "yellow_theme";
    private final String KEY_CHRISTMAS_THEME = "christmas_theme";

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.pref);
        context = this.getApplicationContext();
        barcodeDialog = false;

        //Определяем чек боксы которые будут радио кнопками
        mCheckBoxPreferenceClassicOff = (CheckBoxPreference)findPreference(KEY_CLASSIC_OFF);
        mCheckBoxPreferenceTextOff = (CheckBoxPreference)findPreference(KEY_TEXT_OFF);
        mCheckBoxPreferenceBarCodeOff = (CheckBoxPreference)findPreference(KEY_BARCODE_OFF);
        mCheckBoxPreferenceMyBarCodeOff = (CheckBoxPreference)findPreference(KEY_MY_BARCODE_OFF);

        chbBlueTheme = (CheckBoxPreference)findPreference(KEY_BLUE_THEME);
        chbYellowTheme = (CheckBoxPreference)findPreference(KEY_YELLOW_THEME);
        chbChristmasTheme = (CheckBoxPreference)findPreference(KEY_CHRISTMAS_THEME);

        mCheckBoxPreferenceClassicOff.setOnPreferenceChangeListener(this);
        mCheckBoxPreferenceTextOff.setOnPreferenceChangeListener(this);
        mCheckBoxPreferenceBarCodeOff.setOnPreferenceChangeListener(this);
        mCheckBoxPreferenceMyBarCodeOff.setOnPreferenceChangeListener(this);

        chbBlueTheme.setOnPreferenceChangeListener(this);
        chbYellowTheme.setOnPreferenceChangeListener(this);
        chbChristmasTheme.setOnPreferenceChangeListener(this);

        //google analytics
        if(getResources().getBoolean(R.bool.analytics_enable))
            EasyTracker.getInstance().setContext(context);

        SharedPreferences settings = getSharedPreferences("pref", MODE_PRIVATE);
        int maxRepeatInPref = settings.getInt("maxRepeat", -1);
        String currentBarcode = settings.getString("myBarCode", "");

        if(currentBarcode.length() != 0){
            mCheckBoxPreferenceMyBarCodeOff.setSummary(getResources()
                    .getString(R.string.useMyBarCodeSum)+"\n"+"my current barcode: "+currentBarcode);
        }

        try {
            version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        about = findPreference("about");
        about.setSummary(getString(R.string.aboutSum) + " v." +version);

        about.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference arg0) {
                showAboutDialog();
                return false;
            }
        });

        maxRepeat = findPreference("maxRepeat");
        String value = "10";
        if(maxRepeatInPref != -1)
            value = String.valueOf(maxRepeatInPref);
        String sum = getResources().getString(R.string.maxRepeatSum);
        maxRepeat.setSummary(sum+"\n"+getResources().getString(R.string.current_value)+ " = "+value);
        maxRepeat.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference arg0) {
                setMaxRep();
                return false;
            }
        });

        barCode = findPreference("myBarCode");
        barCode.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference arg0) {
                Intent CameraTestActivity = new Intent(context, CameraTestActivity.class);
                CameraTestActivity.putExtra("AlarmCancel", false);
                startActivity(CameraTestActivity);
                return false;
            }
        });

        rev = findPreference("Review");
        rev.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference arg0) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse("market://details?id=ru.adhoc.truealarmfree"));
                startActivity(intent);
                return false;
            }
        });

        buy = findPreference("buy");
        buy.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference arg0) {
                if(getResources().getBoolean(R.bool.analytics_enable))
                    EasyTracker.getTracker().sendEvent("ui_action","button_press","buy_in_settings_activity", null);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse("market://details?id=ru.adhoc.truealarm&referrer=utm_source%3Dclick_in_freeapp"));
                startActivity(intent);
                return false;
            }
        });
    }

    private void setMaxRep(){

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.enterNumRepeat);
        final SeekBar sb = new SeekBar(this);
        sb.setMax(20);

        //Получим текущие настройки  и покажем их на сик баре
        SharedPreferences settings = getSharedPreferences("pref", MODE_PRIVATE);
        int maxRepeatInPref = settings.getInt("maxRepeat", -1);

        //По умолчанию 15 раз можно отложить
        if(maxRepeatInPref == -1){
            sb.setProgress(10);
            builder.setMessage("10");
        }
        else{
            sb.setProgress(maxRepeatInPref);
            builder.setMessage(String.valueOf(maxRepeatInPref));
        }

        builder.setView(sb);

        builder.setPositiveButton(R.string.btAdd, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {

                String sum = getResources().getString(R.string.maxRepeatSum);
                String value = String.valueOf(sb.getProgress());
                maxRepeat.setSummary(sum+"\n"+getResources().getString(R.string.current_value)+ " = "+value);

                SharedPreferences settings = getSharedPreferences("pref", MODE_PRIVATE);
                SharedPreferences.Editor editor = settings.edit();
                editor.putInt("maxRepeat",sb.getProgress());
                editor.commit();

            }
        });

        builder.setNegativeButton(R.string.btCancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            }
        });

        final AlertDialog AD = builder.create();

        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
                AD.setMessage(String.valueOf(progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        AD.show();

    }

    @Override
    public boolean onPreferenceChange(Preference preference, Object o) {

       String key =  preference.getKey();

        if(key.equalsIgnoreCase(KEY_CLASSIC_OFF)){
            if(!mCheckBoxPreferenceClassicOff.isChecked()){
                mCheckBoxPreferenceTextOff.setChecked(false);
                mCheckBoxPreferenceBarCodeOff.setChecked(false);
                mCheckBoxPreferenceMyBarCodeOff.setChecked(false);
            }
            else {
                if(!mCheckBoxPreferenceTextOff.isChecked() &&
                        !mCheckBoxPreferenceBarCodeOff.isChecked()&&
                        !mCheckBoxPreferenceMyBarCodeOff.isChecked())
                    return false;
            }
        }
        else if(key.equalsIgnoreCase(KEY_TEXT_OFF)){
            if(!mCheckBoxPreferenceTextOff.isChecked()){
                mCheckBoxPreferenceClassicOff.setChecked(false);
                mCheckBoxPreferenceBarCodeOff.setChecked(false);
                mCheckBoxPreferenceMyBarCodeOff.setChecked(false);
            }
            else {
                if(!mCheckBoxPreferenceClassicOff.isChecked() &&
                        !mCheckBoxPreferenceBarCodeOff.isChecked()&&
                        !mCheckBoxPreferenceMyBarCodeOff.isChecked())
                    return false;
            }
        }
        else if(key.equalsIgnoreCase(KEY_BARCODE_OFF)){

            if(!mCheckBoxPreferenceBarCodeOff.isChecked()){
                mCheckBoxPreferenceTextOff.setChecked(false);
                mCheckBoxPreferenceClassicOff.setChecked(false);
                mCheckBoxPreferenceMyBarCodeOff.setChecked(false);
            }
            else {
                if(!mCheckBoxPreferenceClassicOff.isChecked() &&
                        !mCheckBoxPreferenceTextOff.isChecked() &&
                        !mCheckBoxPreferenceMyBarCodeOff.isChecked())
                    return false;
            }
        }

        else if(key.equalsIgnoreCase(KEY_MY_BARCODE_OFF)){
            if(!mCheckBoxPreferenceMyBarCodeOff.isChecked()){
                SharedPreferences settings = getSharedPreferences("pref", MODE_PRIVATE);
                String currentBarcode = settings.getString("myBarCode", "");
                if(currentBarcode.length() ==0){
                    barcodeDialog = true;
                    showDialogNoStoredBarcode();
                    SharedPreferences settings1 = getSharedPreferences("pref", MODE_PRIVATE);
                    String currentBarcode1 = settings1.getString("myBarCode", "");
                    if(currentBarcode1.length() ==0){
                        return false;
                    }
                }
                mCheckBoxPreferenceTextOff.setChecked(false);
                mCheckBoxPreferenceClassicOff.setChecked(false);
                mCheckBoxPreferenceBarCodeOff.setChecked(false);
            }
            else {
                if(!mCheckBoxPreferenceClassicOff.isChecked() &&
                        !mCheckBoxPreferenceTextOff.isChecked() &&
                        !mCheckBoxPreferenceBarCodeOff.isChecked())
                    return false;
            }
        }

       //Обработка раздела темы-------------------------------------------------
       else if(key.equalsIgnoreCase(KEY_BLUE_THEME)){
           if(!chbBlueTheme.isChecked()){
               chbYellowTheme.setChecked(false);
               chbChristmasTheme.setChecked(false);
           }
           else {
               if(!chbYellowTheme.isChecked() &&
                       !chbChristmasTheme.isChecked())
                   return false;
           }
       }

       else if(key.equalsIgnoreCase(KEY_YELLOW_THEME)){
           if(!chbYellowTheme.isChecked()){
               chbBlueTheme.setChecked(false);
               chbChristmasTheme.setChecked(false);
           }
           else {
               if(!chbBlueTheme.isChecked() &&
                       !chbChristmasTheme.isChecked())
                   return false;
           }
       }

       else if(key.equalsIgnoreCase(KEY_CHRISTMAS_THEME)){
           if(!chbChristmasTheme.isChecked()){
               chbBlueTheme.setChecked(false);
               chbYellowTheme.setChecked(false);
           }
           else {
               if(!chbBlueTheme.isChecked() &&
                       !chbYellowTheme.isChecked())
                   return false;
           }
       }

        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_settings, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if(item.getItemId() == R.id.menu_buySettings){
            if(getResources().getBoolean(R.bool.analytics_enable))
                EasyTracker.getTracker().sendEvent("ui_action","button_press","buy_in_settings_activity", null);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("market://details?id=ru.adhoc.truealarm&referrer=utm_source%3Dclick_in_freeapp"));
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }

    private void showAboutDialog(){

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.aboutTitle));
        final TextView message = new TextView(this);
        final SpannableString s =
                new SpannableString("    "+getString(R.string.app_name)+" v."+ version
                        +"\n"+"\n" + getString(R.string.aboutMessage));
        Linkify.addLinks(s, Linkify.WEB_URLS);
        builder.setIcon(R.drawable.ic_launcher);
        message.setText(s);
        message.setMovementMethod(LinkMovementMethod.getInstance());
        message.setTextColor(Color.BLACK);
        builder.setView(message);

        builder.setPositiveButton(R.string.btAdd, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
            }
        });

        AlertDialog AD = builder.create();
        AD.show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(getResources().getBoolean(R.bool.analytics_enable))
            EasyTracker.getInstance().activityStart(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(getResources().getBoolean(R.bool.analytics_enable))
            EasyTracker.getInstance().activityStop(this);
    }

    private void showDialogNoStoredBarcode(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.warning_dialog_title));
        builder.setMessage(getString(R.string.warning_dialog_summary));
        builder.setPositiveButton(getString(R.string.warning_dialog_positive_button),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        saveUserBarcode();
                    }
                });
        builder.setNegativeButton(R.string.btCancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            }
        });

        AlertDialog AD = builder.create();
        AD.show();
    }

    private void saveUserBarcode(){
        Intent CameraTestActivity = new Intent(context, CameraTestActivity.class);
        CameraTestActivity.putExtra("AlarmCancel", false);
        startActivityForResult(CameraTestActivity, 1);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1:
                    if(data.getBooleanExtra("barcodeScanned", false)){
                        SharedPreferences settings = getSharedPreferences("pref", MODE_PRIVATE);
                        String currentBarcode = settings.getString("myBarCode", "");
                        if(currentBarcode.length() !=0){
                            mCheckBoxPreferenceMyBarCodeOff.setSummary(getResources()
                                    .getString(R.string.useMyBarCodeSum)+"\n"+getString(R.string.my_current_barcode)+": "+currentBarcode);
                            if(barcodeDialog){
                                mCheckBoxPreferenceMyBarCodeOff.setChecked(true);
                                mCheckBoxPreferenceTextOff.setChecked(false);
                                mCheckBoxPreferenceClassicOff.setChecked(false);
                                mCheckBoxPreferenceBarCodeOff.setChecked(false);
                            }
                        }
                    }
                    break;
            }
        }
    }
}